<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/29 0029
 * Time: 14:13
 */

namespace app\admin\controller;


use think\Db;

class Backup extends Base
{
    /**(
     * 数据库备份列表页
     * */
    public function lists(){
        return $this->fetch();
    }
    /**
     * 获取列表数据
     * */
    public function getBackListData(){
        $back = new \app\model\model\Backup();
        $where =[];
        $name = input("name");
        if($name){
            $where['name'] = ['like',"%$name%"];
        }
        $data = $back->getList($where,input('limit'));
        foreach ($data as $v){
            $v['size'] = self::byte_format($v['size']);
            $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
        }

        $list = $data->toArray();
        echo json_echo($list);
    }
    /**
     * 获取下载地址
     * */
    public function getUrl(){
        $bacnup = new \app\model\model\Backup();
        $data = $bacnup->getOne(input('id'));
        echo json_encode($data);
    }
    /**
     * 删除一个备份
     * */
    public function del(){
        $bacnup = new \app\model\model\Backup();
        $re = $bacnup->delOne(input('id'));
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(500,'删除失败！');
        }
    }
    public function delAll(){
        $back = new \app\model\model\Backup();
        $re = $back->delAll(input()['data']);
        if($re){
            return json_echo_msg(200,'删除成功！');
        }else{
            return json_echo_msg(500,'删除失败！');
        }
    }
    /**
     * 备份数据库fangfa
     * */
    public function exportDatabase(){
        $path = 'mysql/';
        $database = config('database')['database'];
        $info = "-- ----------------------------\r\n";
        $info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
        $info .= "-- MySQL - 5.5.52-MariaDB : Database - ".$database."\r\n";
        $info .= "-- ----------------------------\r\n\r\n";
        $info .= "CREATE DATAbase IF NOT EXISTS `".$database."` DEFAULT CHARACTER SET utf8 ;\r\n\r\n";
        $info .= "USE `".$database."`;\r\n\r\n";

// 检查目录是否存在
        if(is_dir($path)){
            if(is_writable($path)){
            }else{
                chmod($path,777);
            }
        }else{
            mkdir($path, 777, true);
        }

// 检查文件是否存在
        $time = date("Y-m-d.H-i-s",time());
        $file_name = $path.$database.'-'.$time.'.sql';
        if(file_exists($file_name)){
            echo 400;
            exit;
        }
        file_put_contents($file_name,$info,FILE_APPEND);
//查询数据库的所有表
        $result = Db::query('show tables');
        foreach ($result as $k=>$v) {
//查询表结构
            $val = $v['Tables_in_'.$database];
            $sql_table = "show create table ".$val;
            $res = Db::query($sql_table);
            $info_table = "-- ----------------------------\r\n";
            $info_table .= "-- Table structure for `".$val."`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            $info_table .= "DROP TABLE IF EXISTS `".$val."`;\r\n\r\n";
            $info_table .= $res[0]['Create Table'].";\r\n\r\n";
//查询表数据
            $info_table .= "-- ----------------------------\r\n";
            $info_table .= "-- Data for the table `".$val."`\r\n";
            $info_table .= "-- ----------------------------\r\n\r\n";
            file_put_contents($file_name,$info_table,FILE_APPEND);
            $sql_data = "select * from ".$val;
            $data = Db::query($sql_data);
            $count= count($data);
            if($count<1) continue;
            foreach ($data as $key => $value){
                $sqlStr = "INSERT INTO `".$val."` VALUES (";
                foreach($value as $v_d){
                    $v_d = str_replace("'","\'",$v_d);
                    $sqlStr .= "'".$v_d."', ";
                }
//需要特别注意对数据的单引号进行转义处理
//去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
                $sqlStr .= ");\r\n";
                file_put_contents($file_name,$sqlStr,FILE_APPEND);
            }
            $info = "\r\n";
            file_put_contents($file_name,$info,FILE_APPEND);
        }
        $zip = new \ZipArchive();
        $filename = $path.$database.'-'.$time.'.zip';
        $zip->open($filename,\ZipArchive::CREATE);   //打开压缩包
        $zip->addFile($file_name,basename($file_name));   //向压缩包中添加文件
        $zip->close();  //关闭压缩包
        unlink($file_name);
        $add = [
            'name'=>$database.'-'.$time.'.zip',
            'size'=>filesize($filename),
            'url'=>'/'.$filename,
            'create_time'=>time(),
        ];
        $backup = new \app\model\model\Backup();
        $re = $backup->addOne($add);
        if($re){
           admin_log("备份数据库操作");
            return 200;
        }else{
            return 500;
        }
    }
}